package com.sciencep.pro.admin.system.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.sciencep.pro.admin.system.common.util.UserUtil;
import com.sciencep.pro.common.domain.QueryRequest;
import com.sciencep.pro.common.domain.ResponseResult;
import com.sciencep.pro.common.exception.CustomException;
import com.sciencep.pro.common.utils.ExcelUtil;
import com.sciencep.pro.common.utils.ExportUtil;
import com.sciencep.pro.core.domain.dto.user.UserDetail;
import com.sciencep.pro.core.domain.dto.workdailylog.ReviewTO;
import com.sciencep.pro.core.domain.dto.workdailylog.WorkDailyLogRequestTO;
import com.sciencep.pro.core.domain.dto.workdailylog.WorkLogDetailTO;
import com.sciencep.pro.core.domain.dto.workdailylog.WorkdailyLogTO;
import com.sciencep.pro.core.domain.entity.ProHistory;
import com.sciencep.pro.core.domain.entity.UserWorkdailyLog;
import com.sciencep.pro.core.domain.entity.UserWorkdailyLogBack;
import com.sciencep.pro.core.domain.vo.workdailylog.WorkDailyLogVo;
import com.sciencep.pro.core.service.IProHistoryService;
import com.sciencep.pro.core.service.IUserWorkdailyLogBackService;
import com.sciencep.pro.core.service.IUserWorkdailyLogService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 日志controller
 *
 * @author libe
 */
@RestController
@Slf4j
@RequestMapping("/workdailyLog")
public class WorkDailyLogController {

    @Autowired
    IUserWorkdailyLogService workdailyLogService;

    @Autowired
    IUserWorkdailyLogBackService userWorkdailyLogBackService;

    @Autowired
    private UserUtil userUtil;

    @Autowired
    IProHistoryService proHistoryService;

    String userName = "userName";

    String deptName = "deptName";

    String proNo = "proNo";

    String proName = "proName";

    String devPoint = "devPoint";

    String dailyLog = "dailyLog";

    String tomorrowPlan = "tomorrowPlan";

    @GetMapping("/myLog/list")
    //查询我的日志
    public ResponseResult<Object> getLogList(@RequestParam String month) throws CustomException {

        UserDetail userDetail = userUtil.getCurrentUserDetail();

        return new ResponseResult<>().success(workdailyLogService.getLogList(userDetail.getUserId(), month));
    }

    @GetMapping("/myLog/export")
    public void getMyLogList(HttpServletResponse response, String beginMonth, String endMonth, String userId) throws IOException, CustomException {

        // 导出我的日志
        List<WorkLogDetailTO> result = workdailyLogService.getMyLog(userId, beginMonth, endMonth);

        LinkedHashMap<String, String> titleMap = Maps.newLinkedHashMap();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (WorkLogDetailTO workdailyLogTO : result) {
            if (workdailyLogTO.getWorkDate() != null) {
                try {
                    workdailyLogTO.setWorkDateString(sdf.format(workdailyLogTO.getWorkDate()));
                    workdailyLogTO.setOnDutyTimeString(simpleDateFormat.format(workdailyLogTO.getOnDutyTime()));
                    workdailyLogTO.setOffDutyTimeString(simpleDateFormat.format(workdailyLogTO.getOffDutyTime()));
                } catch (java.lang.NullPointerException e) {
                    log.info("");
                }

            }

        }
        titleMap.put(userName, "用户名称");
        titleMap.put("userDept", "部门ID");
        titleMap.put(deptName, "部门名称");
        titleMap.put(proNo, "项目编号");
        titleMap.put(proName, "项目名称");
        titleMap.put(devPoint, "开发节点");
        titleMap.put("workDateString", "工作日期");
        titleMap.put("putinDaily", "投入人天");
        titleMap.put("performanceDaily", "绩效人天");
        titleMap.put("onDutyTimeString", "实际上班时间");
        titleMap.put("offDutyTimeString", "实际下班时间");
        titleMap.put(dailyLog, "工作日志");
        titleMap.put("remark", "备注");
        titleMap.put(tomorrowPlan, "明日计划");
        titleMap.put("reviewStatusString", "审核状态名称");
        int[] size = {40, 26, 26, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30};
        result.add(new WorkLogDetailTO());
        ExportUtil.exportExcelToReponse(response, titleMap, result, "我的日志", size);

    }

    @GetMapping("/myLog/detail")
    public ResponseResult<Object> getLogDetail(@RequestParam String date, String proNo) throws CustomException {

        UserDetail userDetail = userUtil.getCurrentUserDetail();
        String userId = userDetail.getUserId();


        return new ResponseResult<>().success(workdailyLogService.getDetail(userId, date, proNo));
    }

    @GetMapping("/getWorkDailyLogList")
    @ApiOperation("查询日志评审列表")
    public ResponseResult<Page<WorkLogDetailTO>> getWorkDailyLogList(QueryRequest queryRequest, WorkDailyLogRequestTO requestTO) throws CustomException {

        String userId = userUtil.getCurrentUserDetail().getUserId();
        requestTO.setMangerId(userId);
        return new ResponseResult<Page<WorkLogDetailTO>>().success(workdailyLogService.getWorkLogDetailTOPage(queryRequest, requestTO));
    }

    @GetMapping("/getWorkDailyLogListNew")
    @ApiOperation("查询日志评审列表")
    public ResponseResult<Page<WorkLogDetailTO>> getWorkDailyLogListNew(QueryRequest queryRequest, WorkDailyLogRequestTO requestTO) throws CustomException {

        String userId = userUtil.getCurrentUserDetail().getUserId();
        requestTO.setMangerId(userId);
        return new ResponseResult<Page<WorkLogDetailTO>>().success(workdailyLogService.getWorkLogDetailTOPageNew(queryRequest, requestTO));
    }

    @PostMapping("/reviewWorkDailyLog")
    @ApiOperation("单条日志评审")
    public ResponseResult<Object> reviewWorkDailyLog(@RequestBody ReviewTO reviewTO) throws CustomException {

        UserDetail detail = userUtil.getCurrentUserDetail();
        workdailyLogService.reviewWorkDailyLog(reviewTO, detail);

        return new ResponseResult<>().success();
    }

    @PostMapping("/reviewWorkDailyLogBatch")
    @ApiOperation("批量日志评审")
    public ResponseResult<Object> reviewWorkDailyLogBatch(@RequestBody List<String> idList) throws CustomException {

        UserDetail detail = userUtil.getCurrentUserDetail();
        workdailyLogService.reviewWorkDailyLogBatch(idList, detail);

        return new ResponseResult<>().success();
    }

    @GetMapping(value = "/getWorkDailyReviewList")
    @ApiOperation(value = "查询人天复核列表")
    public ResponseResult<Object> getWorkDailyReviewList(QueryRequest queryRequest, WorkDailyLogVo workDailyLogVo) {
        Page<WorkdailyLogTO> result = workdailyLogService.getWorkDailyReviewList(queryRequest, workDailyLogVo);
        return new ResponseResult<>().success(result);
    }

    @GetMapping(value = "/getWorkDailyReviewListBack")
    @ApiOperation(value = "查询备份表的人天复核列表")
    public ResponseResult<Object> getWorkDailyReviewListBack(QueryRequest queryRequest, WorkDailyLogVo workDailyLogVo) {
        Page<WorkdailyLogTO> result = workdailyLogService.getWorkDailyReviewListBack(queryRequest, workDailyLogVo);
        return new ResponseResult<>().success(result);
    }

    @GetMapping(value = "/getDeptList")
    @ApiOperation(value = "查询人天明细")
    public ResponseResult<List<UserWorkdailyLog>> getDeptList(WorkDailyLogVo workDailyLogVo) {
        List<UserWorkdailyLog> userWorkdailyLogList = workdailyLogService.list(new LambdaQueryWrapper<UserWorkdailyLog>().
                eq(UserWorkdailyLog::getUserId, workDailyLogVo.getUserId()).
                eq(UserWorkdailyLog::getWorkDate, workDailyLogVo.getWorkDate()).
                eq(StringUtils.isNotBlank(workDailyLogVo.getProNo()), UserWorkdailyLog::getProNo, workDailyLogVo.getProNo()));
        //20210125 新需求
        if(CollUtil.isEmpty(userWorkdailyLogList)){
            Calendar currCal=Calendar.getInstance();
            int currentYear = currCal.get(Calendar.YEAR);
            Calendar calendar = Calendar.getInstance();
            calendar.clear();
            calendar.set(Calendar.YEAR, currentYear);
            Date currYearFirst = calendar.getTime();
            proHistoryService.list(new LambdaQueryWrapper<ProHistory>().eq(ProHistory::getProCode,workDailyLogVo.getProNo()).eq(ProHistory::getProUserName,workDailyLogVo.getUserName())).forEach(e->{
                UserWorkdailyLog userWorkdailyLog = new UserWorkdailyLog();
                userWorkdailyLog.setWorkDate(currYearFirst);
                userWorkdailyLog.setProName(e.getProName());
                userWorkdailyLog.setPutinDaily(e.getRealInputHours());
                userWorkdailyLog.setPerformanceDaily(e.getRealPerformanceHours());
                userWorkdailyLogList.add(userWorkdailyLog);
            });
        }
        return new ResponseResult<List<UserWorkdailyLog>>().success(userWorkdailyLogList);
    }

    @GetMapping(value = "/getDeptListBack")
    @ApiOperation(value = "查询人天明细")
    public ResponseResult<List<UserWorkdailyLogBack>> getDeptListBack(WorkDailyLogVo workDailyLogVo) {
        List<UserWorkdailyLogBack> userWorkdailyLogBackList;
        if (workDailyLogVo.getType().equals("1")) {
            userWorkdailyLogBackList = userWorkdailyLogBackService.list(new LambdaQueryWrapper<UserWorkdailyLogBack>().
                    eq(UserWorkdailyLogBack::getUserId, workDailyLogVo.getUserId()).
                    eq(UserWorkdailyLogBack::getWorkDate, workDailyLogVo.getWorkDate()).
                    eq(StringUtils.isNotBlank(workDailyLogVo.getProNo()), UserWorkdailyLogBack::getProNo, workDailyLogVo.getProNo()));
        } else {
            userWorkdailyLogBackList = userWorkdailyLogBackService.list(new LambdaQueryWrapper<UserWorkdailyLogBack>().
                    eq(UserWorkdailyLogBack::getUserName, workDailyLogVo.getUserName()).
                    eq(UserWorkdailyLogBack::getWorkDate, workDailyLogVo.getWorkDate()).
                    eq(StringUtils.isNotBlank(workDailyLogVo.getProNo()), UserWorkdailyLogBack::getProNo, workDailyLogVo.getProNo()));
        }
        return new ResponseResult<List<UserWorkdailyLogBack>>().success(userWorkdailyLogBackList);
    }

    @GetMapping(value = "/exportWorkDailyReview")
    @ApiOperation(value = "导出人天复核列表")
    public void exportWorkDailyReviewList(HttpServletResponse response, WorkDailyLogVo workDailyLogVo) throws IOException, CustomException {
        List<WorkdailyLogTO> result = workdailyLogService.getWorkDailyReviewListExport(workDailyLogVo);
        LinkedHashMap<String, String> titleMap = Maps.newLinkedHashMap();
        titleMap.put(userName, "用户名称");
        titleMap.put(deptName, "部门名称");
        titleMap.put(proNo, "项目编号");
        titleMap.put(proName, "项目名称");
        titleMap.put("date", "打卡日期");
        titleMap.put("isResignStr", "在职状态");
        titleMap.put("sumPutinDaily", "投入人天");
        titleMap.put("sumPerformanceDaily", "绩效人天");
        titleMap.put("nodeName", "项目节点");
        titleMap.put(devPoint, "开发节点");
        titleMap.put(dailyLog, "今日工作");
        titleMap.put(tomorrowPlan, "明日工作");
        titleMap.put("dailyRemark", "日志备注");
        titleMap.put("onDutyTime", "上班时间");
        titleMap.put("offDutyTime", "下班时间");
        titleMap.put("attendanceRemark", "考勤备注");
        titleMap.put("leaveRemark", "请假备注");
        int[] size = {10, 20, 20, 20, 10, 10, 10, 10, 10, 10, 30, 30, 30, 20, 20, 30, 30};
        ExportUtil.exportExcelToReponse(response, titleMap, result, "人天统计", size);
    }

    @GetMapping(value = "/exportWorkDailyReviewDetail")
    @ApiOperation(value = "导出人天日志修改详情")
    public void exportWorkDailyReviewDetail(HttpServletResponse response, WorkDailyLogVo workDailyLogVo) throws IOException, CustomException {
        List<WorkdailyLogTO> result = workdailyLogService.exportWorkDailyReviewDetail(workDailyLogVo);
        LinkedHashMap<String, String> titleMap = Maps.newLinkedHashMap();
        titleMap.put("id", "ID(无需输入)");
        titleMap.put("attendanceId", "打卡ID(无需输入)");
        titleMap.put("userId", "员工ID");
        titleMap.put(userName, "用户名称");
        titleMap.put("deptId", "部门ID");
        titleMap.put(deptName, "部门名称");
        titleMap.put("date", "打卡日期");
        titleMap.put("isResignStr", "在职状态");
        titleMap.put(proNo, "项目编号");
        titleMap.put(proName, "项目名称");
        titleMap.put("sumPutinDaily", "投入人天");
        titleMap.put("sumPerformanceDaily", "绩效人天");
        titleMap.put("nodeName", "项目节点");
        titleMap.put(devPoint, "开发节点");
        titleMap.put(dailyLog, "今日工作");
        titleMap.put(tomorrowPlan, "明日工作");
        titleMap.put("dailyRemark", "日志备注");
        titleMap.put("onDutyTime", "上班打卡时间");
        titleMap.put("offDutyTime", "下班打卡时间");
        titleMap.put("attendanceRemark", "考勤备注");
        titleMap.put("leaveRemark", "请假备注");
        int[] size = {0, 0, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 30, 20, 20, 26, 26, 30, 30};
        ExportUtil.exportExcelToReponse(response, titleMap, result, "人天审查", size);
    }

    @PostMapping(value = "/importWorkDailyReviewDetail")
    @ApiOperation(value = "导入人天复核详情")
    public ResponseResult<UserWorkdailyLog> importWorkDailyReviewDetail(MultipartFile file) throws CustomException, ParseException, IOException {
        ExcelUtil excelUtil = new ExcelUtil();
        List<WorkdailyLogTO> list = excelUtil.readExcelFileToDTO(file, WorkdailyLogTO.class, 0);
        UserDetail detail = userUtil.getCurrentUserDetail();
        return workdailyLogService.importWorkDailyReviewDetail(list, detail);
    }



}
